import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_add_save_user_dialog/common_ave_user_tips_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/create_user/create_user/bean/create_user_upload_bean.dart';
import 'package:e_reception_flutter/ui/create_user/create_user/widgets/create_user_edit_widget.dart';
import 'package:e_reception_flutter/ui/mypage/toolTipBoxNewPage.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';

import 'create_user_page_view_model.dart';

/// 创建用户页面
///
/// @author: zengxiangxi
/// @createTime: 3/10/21 10:34 AM
/// @specialDemand:
class CreateUserPage extends StatefulWidget {
  final bool firstSaveUserTips;
  final String role;

  const CreateUserPage({Key key, this.role, this.firstSaveUserTips})
      : super(key: key);

  @override
  CreateUserPageState createState() => CreateUserPageState();

  ///跳转方法
  static Future<bool> navigatorPush(BuildContext context, {String role}) {
    return RouterUtils.routeForFutureResult<bool>(
      context,
      CreateUserPage(role: role),
    )..then((value) {
        // _checkCacheUseCount(context,value);
      });
  }

  static const String _SP_ADD_SAVE_USER_KEY = "SP_addSaveUser";

  //检查缓存使用次数
  static void _checkCacheUseCount(BuildContext context, bool result) async {
    if (!(result ?? false)) {
      return;
    }
    bool useResult = await SharePreferenceUtil.getBool(_SP_ADD_SAVE_USER_KEY);
    if (!(useResult ?? false)) {
      //弹出对话框
      AddSaveUserTipsFaceMatching.navigatorPushDialog(context);
      SharePreferenceUtil.putBool(_SP_ADD_SAVE_USER_KEY, true);
    }
  }
}

class CreateUserPageState extends BaseState<CreateUserPage> {

  //是否有保存过用户
  bool firstSaveUserTips = true;

  //设置缓存值
  static const String SP_ADD_SAVE_USER_KEY = "SP_addSaveUser";

  CreateUserPageViewModel _viewModel;

  CreateUserUploadBean _mUploadBean;

  ValueNotifier<bool> _isAllowConfirmValueNotifier;

  ValueNotifier<String> _updateNickValueNotifier;

  @override
  void initState() {
    super.initState();
    _viewModel = CreateUserPageViewModel(this);
    _updateNickValueNotifier = ValueNotifier(null);
    _isAllowConfirmValueNotifier = ValueNotifier(false);
    _mUploadBean = CreateUserUploadBean();
    //变化监听
    _mUploadBean.addListener(_notifyValue);
  }

  @override
  void dispose() {
    _isAllowConfirmValueNotifier.dispose();
    _updateNickValueNotifier?.dispose();
    _mUploadBean.removeListener(_notifyValue);
    super.dispose();
  }

  void _notifyValue() {
    // print("数据更新了: ${_mUploadBean.toString()}");
    String errorMsg = _mUploadBean.checkAllowConfirmForErrorMsg();
    if (errorMsg == null || errorMsg.isEmpty) {
      _isAllowConfirmValueNotifier.value = true;
    } else {
      // VgToastUtils.toast(context, errorMsg);
      _isAllowConfirmValueNotifier.value = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      resizeToAvoidBottomPadding: false,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: CommonPackUpKeyboardWidget(child: _toMainColumnWidget()),
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        Expanded(
            child: CreateUserEditWidget(
          uploadBean: _mUploadBean,
          updateNameValueNotifier: _updateNickValueNotifier,
          role: widget.role,
        )),
      ],
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      isShowBack: true,
      title: "添加用户",
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: ValueListenableBuilder(
        valueListenable: _isAllowConfirmValueNotifier,
        builder: (BuildContext context, bool isAllowConfirm, Widget child) {
          return GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () async {
              VgToolUtils.removeAllFocus(context);
              String errorMsg = _mUploadBean.checkAllowConfirmForErrorMsg();
              if (errorMsg != null && errorMsg.isNotEmpty) {
                _isAllowConfirmValueNotifier.value = false;
                VgToastUtils.toast(context, errorMsg);
                return;
              }
              _isAllowConfirmValueNotifier.value = true;
              //保存此次添加的方式
              SharePreferenceUtil.putString(KEY_LAST_ADD_USER_TYPE +
                  UserRepository.getInstance().getCacheKeySuffix(),_mUploadBean.groupBean.groupid);

              //判断添加的如果是家长则走此接口
              if(_mUploadBean?.groupBean?.groupName=="家长"){
                _viewModel.saveParentUserHttp(context, _mUploadBean);
              }else{
                _viewModel.saveUserHttp(context, _mUploadBean);
              }
            },
            child: CommonFixedHeightConfirmButtonWidget(
              isAlive: isAllowConfirm,
              width: 48,
              height: 24,
              unSelectBgColor:
                  ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
              selectedBgColor:
                  ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              unSelectTextStyle: TextStyle(
                  color: VgColors.INPUT_BG_COLOR,
                  fontSize: 12,
                  fontWeight: FontWeight.w600),
              selectedTextStyle: TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.w600),
              text: "保存",
            ),
          );
        },
      ),
    );
  }

  void pushNameRepeatDialog() async {
    String nick = await ToolTipBoxNewPage.navigatorPushDialog(context);
    if (nick == null || nick.isEmpty) {
      return;
    }
    _updateNickValueNotifier.value = nick;
    _mUploadBean.nick = nick;
    Future(() {
      _viewModel.saveUserHttp(context, _mUploadBean);
    });
    return;
  }
}
